<template>
  <div class="app-container">
    <div style="margin-bottom: 10px">
      <el-button
        @click="dialogVisible = true"
        type="primary"
        size="mini"
        icon="el-icon-download"
      >
        导入Excel
      </el-button>

      <el-button
        @click="exportData"
        type="primary"
        size="mini"
        icon="el-icon-upload2"
      >
        导出Excel
      </el-button>
    </div>

    <el-dialog title="数据字典导入" :visible.sync="dialogVisible" width="23%">
      <el-form>
        <el-form-item>
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="true"
            :multiple="false"
            :limit="1"
            :on-exceed="fileUploadExceed"
            :on-success="fileUploadSuccess"
            :on-error="fileUploadError"
            :action="BASE_API + '/admin/core/dict/import'"
            name="file"
            accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">请选择Excel文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 展示表格 -->
    <el-table :data="list" border row-key="id" lazy :load="load">
      <el-table-column label="名称" align="left" prop="name" />
      <el-table-column label="编码" prop="dictCode" />
      <el-table-column label="值" align="left" prop="value" />
    </el-table>
  </div>
</template>

<script>
import { listByParentId } from '@/api/core/dict'
export default {
  name: '',
  data() {
    return {
      list: [],
      dialogVisible: false,
      BASE_API: process.env.VUE_APP_BASE_API, //获取后端接口地址
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    //配合limit使用，只能上传一个文件
    fileUploadExceed() {
      this.$message.warning('只能上传一个文件')
    },
    //上传成功
    fileUploadSuccess(resp) {
      if (resp.code === 0) {
        this.$message.success('数据导入成功')
        this.dialogVisible = false
      } else {
        this.$message.error(resp.message)
      }
    },

    //通信失败
    fileUploadError() {
      this.$message.error('数据导入失败')
    },

    //导出
    exportData() {
      window.location.href = this.BASE_API + '/admin/core/dict/export'
    },

    //查找一级节点
    fetchData() {
      listByParentId(1).then((resp) => {
        this.list = resp.data
      })
    },

    //懒加载子节点
    load(tree, treeNode, resolve) {
       listByParentId(tree.id).then((resp) => {
        resolve(resp.data)
      })
    }
  },
  mounted() {},
}
</script>

<style scoped>
</style>
